package StudyCode.summary.csv;

import java.util.ArrayList;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ParseLineCSVReturnStringsList {

	public static void main(String[] args) {
		String str = "www.tah1986.com";
		System.out.println("解析前: " + str);
		System.out.println("解析后: " + parseCSV(str, "."));
	}

	public static ArrayList parseCSV(String data, String delimiter) {

		String enclosure = "\"";
		String newline = "\n";

		int pos = -1;
		int last_pos = -1;
		int end = data.length();

		int row = 0;
		boolean quote_open = false;
		boolean trim_quote = false;

		ArrayList returnCells = new ArrayList();

		for (int i = -1; ; ++i) {
			++pos;
			int comma_pos = data.indexOf(delimiter, pos);
			int quote_pos = data.indexOf(enclosure, pos);
			int newline_pos = data.indexOf(newline, pos);

			// Which one comes first?
			pos = min((comma_pos == -1) ? end : comma_pos,
					(quote_pos == -1) ? end : quote_pos,
					(newline_pos == -1) ? end : newline_pos);

			String character = "";

			boolean done = false;

			if (pos >= data.length() - 1) {
				done = true;
			} else {
				character = data.substring(pos, pos + 1);
			}

			if (pos == end) {
				done = true;
			}

			if (done || (character.compareTo(delimiter) == 0)
					|| character.compareTo(newline) == 0) {

				if (quote_open && !done) {
					continue;
				}

				int length = pos - ++last_pos;

				if (character.compareTo(newline) == 0) {
					--length;
				}

				if (trim_quote) {
					--length;
				}

				String nextCell = "";

				if (length > 0) {
					nextCell = data.substring(last_pos, last_pos + length)
							.replace(enclosure + enclosure, enclosure);
				}

				returnCells.add(nextCell);


				if (done) {
					break;
				}

				last_pos = pos;

				if (character.compareTo(newline) == 0) {
					++row;
				}

				trim_quote = false;
			} else if (character.compareTo(enclosure) == 0) {

				if (quote_open == false) {
					quote_open = true;
					trim_quote = false;

					if (last_pos + 1 == pos) {
						++last_pos;
					}
				} else {
					quote_open = false;

					trim_quote = true;
				}
			}
		}

		return returnCells;
	}


	public static int min(int a, int b, int c) {
		int low1 = Math.min(a, b);
		int low2 = Math.min(b, c);
		return Math.min(low1, low2);
	}
}
